<template>
    <div>
        <el-page-header icon="" content="添加产品" title="产品管理"></el-page-header>

        <el-form ref="productFormRef"  status-icon :model="productForm" :rules="productFormRules" label-width="auto" class="demo-ruleForm">

            <el-form-item label="产品名称" prop="title">
                <el-input v-model="productForm.title" />
            </el-form-item>

            <el-form-item label="产品简要描述" prop="introduction">
                <el-input v-model="productForm.introduction" type="textarea"/>
            </el-form-item>

            <el-form-item label="产品详细描述" prop="detail">
                <el-input v-model="productForm.detail" type="textarea"/>
            </el-form-item>

            <el-form-item label="产品图片" prop="cover">
                <Upload :avatar = "productForm.cover" @fileChange="handleChange"></Upload>
            </el-form-item>

            <el-form-item class="label">
                <el-button type="primary" @click="submitForm()" style="margin: 0 auto;">添加产品</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {ref,reactive} from 'vue'
import {useRouter} from 'vue-router'
import Upload from '@/components/upload/Upload.vue';
import upload from '@/util/upload'

const productFormRef = ref()
const router = useRouter()
const productForm = reactive({
    title:"",
    introduction:"",
    detail:"",
    cover:"",
    file:null
})

const productFormRules = reactive({
    title: [
        { required: true, message: '输入名字', trigger: 'blur' },
    ],
    detail: [
        { required: true, message: '输入详细描述', trigger: 'blur' },
    ],
    cover: [
        { required: true, message: '上传产品图片', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '输入简要描述', trigger: 'blur' },
    ]
})

//选择完头像后的回调
const handleChange = (file) =>{
    productForm.cover = URL.createObjectURL(file)
    productForm.file = file
} 

const submitForm = ()=>{
    productFormRef.value.validate(async (valid)=>{
        if(valid){
            await upload('/adminapi/product/add',productForm)
            router.push('/product-manage/productlist')
        }
    })
}

</script>

<style scoped>
.demo-ruleForm{
    margin-top: 50px;
}
</style>